package com.example.acountingappliaction; // 修正包名拼写

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.acountingappliaction.DBHelper;
import com.example.acountingappliaction.User;
import com.google.android.material.textfield.TextInputEditText;

public class Register_activity extends AppCompatActivity {

    private TextInputEditText etUsername, etPassword, etConfirmPassword;
    private Button btnRegister;
    private TextView tvGoLogin;
    private DBHelper dbHelper;
    private Animation scaleInAnim, shakeAnim;

    // 错误状态标记
    private boolean isUsernameError = false;
    private boolean isPasswordError = false;
    private boolean isConfirmError = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化动画
        scaleInAnim = AnimationUtils.loadAnimation(this, R.anim.scale_in);
        shakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake); // 缓存动画资源

        // 初始化数据库
        dbHelper = new DBHelper(this);

        // 初始化控件
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        btnRegister = findViewById(R.id.btn_register);
        tvGoLogin = findViewById(R.id.tv_go_login);

        // 设置输入监听
        setupTextWatchers();

        // 注册按钮点击
        btnRegister.setOnClickListener(v -> {
            v.startAnimation(scaleInAnim);
            register();
        });

        // 登录跳转
        tvGoLogin.setOnClickListener(v -> {
            v.startAnimation(scaleInAnim);
            finish();
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        });
    }

    /**
     * 设置输入框文本变化监听器，实时校验
     */
    private void setupTextWatchers() {
        // 用户名输入监听（检测是否已被注册）
        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String username = s.toString().trim();
                if (username.isEmpty()) {
                    resetEditTextState(etUsername);
                    isUsernameError = false;
                } else {
                    // 实时检查用户名是否已存在
                    User existingUser = dbHelper.queryUserByUsername(username);
                    if (existingUser != null) {
                        showError(etUsername, "用户名已存在", true);
                    } else if (isUsernameError) {
                        resetEditTextState(etUsername);
                        isUsernameError = false;
                    }
                }
            }
        });

        // 密码输入监听（密码变化时重新校验确认密码）
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                checkPasswordMatch();
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        // 确认密码输入监听（实时校验与密码是否一致）
        etConfirmPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                checkPasswordMatch();
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    /**
     * 校验两次输入的密码是否一致
     */
    private void checkPasswordMatch() {
        String password = etPassword.getText().toString().trim();
        String confirm = etConfirmPassword.getText().toString().trim();

        if (!confirm.isEmpty() && !password.equals(confirm)) {
            // 密码不一致，显示错误
            if (!isConfirmError) {
                showError(etConfirmPassword, getString(R.string.password_not_match), true);
            }
        } else if (isConfirmError) {
            // 密码一致，恢复正常状态
            resetEditTextState(etConfirmPassword);
            isConfirmError = false;
        }
    }

    private void register() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        // 重置所有错误状态
        resetAllErrors();

        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(btnRegister.getWindowToken(), 0);
        }

        // 输入验证
        if (username.isEmpty()) {
            showError(etUsername, "请输入用户名", true);
            return;
        }

        // 校验用户名格式（3-20位字母、数字或下划线）
        if (!isValidUsername(username)) {
            showError(etUsername, "用户名需为3-20位字母、数字或下划线", true);
            return;
        }

        if (password.isEmpty()) {
            showError(etPassword, "请输入密码", true);
            return;
        }

        if (confirmPassword.isEmpty()) {
            showError(etConfirmPassword, "请确认密码", true);
            return;
        }

        // 检查密码一致性
        if (!password.equals(confirmPassword)) {
            String errorMsg = getString(R.string.password_not_match);
            showError(etConfirmPassword, errorMsg, true);
            Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查用户名是否存在
        if (dbHelper.queryUserByUsername(username) != null) {
            String errorMsg = "用户名已被注册";
            showError(etUsername, errorMsg, true);
            Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
            return;
        }

        // 注册用户 - 使用加密密码（这里假设DBHelper.register方法已支持加密）
        // 注意：实际项目中应在此处加密密码
        User newUser = new User(username, password);
        long rowId = dbHelper.register(newUser);
        if (rowId != -1) {
            Toast.makeText(this, R.string.register_success, Toast.LENGTH_SHORT).show();
            // 清空输入框
            etUsername.getText().clear();
            etPassword.getText().clear();
            etConfirmPassword.getText().clear();
            finish();
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        } else {
            Toast.makeText(this, "注册失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 验证用户名格式
     */
    private boolean isValidUsername(String username) {
        return username.matches("^[a-zA-Z0-9_]{3,20}$");
    }

    /**
     * 显示错误状态
     * @param editText 输入框
     * @param message 错误信息
     * @param isError 是否标记为错误状态
     */
    private void showError(EditText editText, String message, boolean isError) {
        editText.setError(message);
        editText.requestFocus();
        editText.startAnimation(shakeAnim); // 使用缓存的动画
        // 设置红色错误背景（使用登录页面中创建的error_bg.xml）
        editText.setBackgroundResource(R.drawable.error_bg);

        // 更新错误状态标记
        if (editText == etUsername) {
            isUsernameError = isError;
        } else if (editText == etPassword) {
            isPasswordError = isError;
        } else if (editText == etConfirmPassword) {
            isConfirmError = isError;
        }
    }

    /**
     * 重置输入框为正常状态
     */
    private void resetEditTextState(EditText editText) {
        editText.setError(null);
        // 恢复默认背景（使用登录页面中创建的default_edittext_bg.xml）
        editText.setBackgroundResource(R.drawable.default_edittext_bg);
    }

    /**
     * 重置所有输入框的错误状态
     */
    private void resetAllErrors() {
        if (isUsernameError) {
            resetEditTextState(etUsername);
            isUsernameError = false;
        }
        if (isPasswordError) {
            resetEditTextState(etPassword);
            isPasswordError = false;
        }
        if (isConfirmError) {
            resetEditTextState(etConfirmPassword);
            isConfirmError = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }
}